package com.yeetrack.baidu.yinyueyun;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jodd.http.Cookie;
import jodd.http.HttpBrowser;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import jodd.io.FileUtil;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

import java.io.File;

/**
 * Created by kongkong on 17/1/13.
 * blog: http://www.yeetrack.com
 * email: wangxuemeng90@126.com
 * 从douban.fm中批量下载自己收藏的音乐
 * 下载到项目根路径douban文件夹中
 */
public class DoubanMain {
	private static final Logger logger = Logger.getLogger(DoubanMain.class);
	private static HttpBrowser httpBrowser = new HttpBrowser();
	private static String username = "username";
	private static String password = "password";
	public static void main(String[] args) {
		BasicConfigurator.configure();
		if(args.length == 2) {
			username = args[0];
			password = args[1];
		}

		//登录
		if(! login()) {
			logger.error("login failed");
			System.exit(1);
		}
		//获取豆瓣fm中红心收藏的音乐
		HttpResponse getResponse = httpBrowser.sendRequest(HttpRequest.get("https://douban.fm/j/v2/redheart/basic"));
		String sidSongs = getResponse.bodyText();

		JSONObject jsonObject = JSON.parseObject(sidSongs);
		JSONArray songArray = jsonObject.getJSONArray("songs");
		int size = songArray.size();
		logger.info("song size: " + songArray.size());
		StringBuilder stringBuilder = new StringBuilder();
		for(int i=0;i< size; i++) {
			String sid = songArray.getJSONObject(i).getString("sid");
			stringBuilder.append(sid).append("|");
		}
		String sids = stringBuilder.substring(0, stringBuilder.length()-1);
		String ckValue = "gGu0";
		Cookie[] cookies = httpBrowser.getHttpResponse().cookies();
		for(Cookie cookie : cookies) {
			if("ck".equals(cookie.getName())) {
				ckValue = cookie.getValue();
				break;
			}
		}
		//获取音乐的真实地址
		HttpRequest request = HttpRequest.post("https://douban.fm/j/v2/redheart/songs")
				.header("Referer", "https://douban.fm/mine/")
				.form("sids", sids)
				.form("kbps", "320")
				.form("ck", ckValue);
		HttpResponse httpResponse = httpBrowser.sendRequest(request);
		String resBody = httpResponse.bodyText();
		JSONArray jsonArray = JSON.parseArray(resBody);
		int songSize = jsonArray.size();
		int downloadCount = 0;
		for(int i=0;i<songSize;i++) {
			JSONObject object = jsonArray.getJSONObject(i);
			String url = object.getString("url");
			String title = object.getString("title");
			String fileExt = object.getString("file_ext");
			//有些翻唱的音乐,歌名会相同
			String artist = object.getString("artist");

			logger.info(url+", " + title);
			//有些音乐文件名中含有/,和文件路径/冲突,修改一下
			String songFileName = (title + "_" + artist + "." + fileExt).replace("/", "_");
			downloadMusic(url, "douban", songFileName);
		}
		logger.info("成功下载音乐: " + downloadCount);
	}

	/**
	 * douban fm通过前端搜索就能拿到真实的下载地址,并且没有校验版权;安全漏洞
	 * https://douban.fm/j/v2/query/all?q=Kung+Fu+Fighting&start=0&limit=5
	 * todo 以后再写吧
	 */
	public static void downloadBySid(String sid) {

	}

	/**
	 * login
	 */
	public static boolean login() {
		httpBrowser.setDefaultHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:59.0) Gecko/20100101 Firefox/59.0");
		httpBrowser.setDefaultHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		httpBrowser.setDefaultHeader("Upgrade-Insecure-Requests", "1");
		httpBrowser.setKeepAlive(true);
		httpBrowser.sendRequest(HttpRequest.get("https://douban.fm/mine/"));//发送请求,获取bid这个cookie
		//用户名密码登录豆瓣fm
		HttpRequest login = HttpRequest.post("https://accounts.douban.com/j/popup/login/basic")
				.query("captcha_id", "")
				.query("captcha_solution", "")
				.query("ck", "")
				.query("name", username)
				.query("password", password)
				.query("referer", "https://douban.fm/")
				.query("source", "fm")
				.header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
				.header("X-Requested-With", "XMLHttpRequest");
		HttpResponse loginResponse = httpBrowser.sendRequest(login);
		String loginResult = loginResponse.bodyText();
		JSONObject loginJson = JSON.parseObject(loginResult);
		//检测是否登录成功
		if("success".equals(loginJson.getString("status"))) {
			logger.info("login success");
			return true;
		} else {
			logger.error("login failed");
			logger.error(loginResult);
			return false;
		}
	}

	/**
	 * download music
	 */
	public static void downloadMusic(String musicUrl, String dir, String fileName) {
		try {
			File dirFile = new File(dir);
			if(!dirFile.exists() || !dirFile.isDirectory()) {
				dirFile.mkdirs();
			}
			//有些音乐文件名中含有/,和文件路径/冲突,修改一下
			File songFile = new File(dir + fileName.replace("/", "_"));
			if(!songFile.exists()) {
				HttpRequest httpRequest = HttpRequest.get(musicUrl);
				HttpResponse response = httpRequest.send();
				FileUtil.writeBytes(songFile, response.bodyBytes());
			} else {
				logger.info(songFile.getName() + ", 已经存在, 忽略");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
